export const axios = require('axios');
export const mockjs = require('mockjs');
export const { getExportObject, assignBest } = require('./utils');
export const request = axios.create();
export default class Api {
    constructor(config) {
        this.getConfig = () =>config;
        let $request = {};
        const toMock = object => {
            const Mock = mockjs;
            for (const key in object) {
                if (typeof object[key] === 'string') {
                    object[key] = { url: object[key] };
                } else if (typeof object[key] === 'object') {
                    let { mockConfig, method, url } = object[key];
                    if (Mock && mockConfig && mockConfig.employ) {
                        Mock.mock(RegExp(`(${url}$)|(${url}[?].*$)`), method, mockConfig.template);
                    }
                }
            }
        };
        toMock(config);
        for (const k in config) {
            $request[k] = new Proxy(config[k], {
                get(apiConfig, method) {
                    return (data = {}, config = {}) =>
                        request(
                            assignBest(
                                {
                                    method,
                                    ...apiConfig
                                },
                                /PUT|POST|PATCH/i.test(method) ? { data } : { params: data },
                                config
                            )
                        );
                }
            });
        }
        Object.assign(this, $request);
    }
}

export const getPathFileApi = modulesFiles =>{
    const exportObject = getExportObject(modulesFiles, false);
    const allApi = {};
    const filterFile = (arr, val) => {
        let o = allApi;
        for (let i = 0; i < arr.length; i++) {
            if (i === arr.length - 1) {
                o[arr[i]] = Object.assign(new Api(val));
            } else {
                o[arr[i]] || (o[arr[i]] = new Api());
                o = o[arr[i]];
            }
        }
    };
    for (const key in exportObject) {
        let val = exportObject[key];
        let keys = key.split('/');
        filterFile(keys, val);
    }
    return allApi
}

